package com.cjbdi.controller;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjbdi.util.MD5Util;
import com.cjbdi.util.PropertiesUtil;
import com.cjbdi.vo.Result;

@Controller
public class ManagerLoginController{

	private String access_token = "";

	/**
	 * 登录
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = { "/managerLogin" }, method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json" })
	@ResponseBody
	public Result login(HttpServletResponse response,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true ) String password) throws UnsupportedEncodingException{
		response.setHeader("Access-Control-Allow-Origin", "*");
		Date now = new Date();
		if((!access_token.equals(""))&&(username.equals(PropertiesUtil.getProperty("username")))&&(password.equals(MD5Util.GetMD5Code(access_token+PropertiesUtil.getProperty("password"))))){
			Date now1 = new Date();
			System.out.println("use login condtion: username"+username+",cost: " + (now1.getTime() - now.getTime()) + " ms");
		}else{
			System.out.println("use login error : username or password is not matched");
			return new Result(402, "用户名和密码不匹配", null);
		}
		return new Result(200, "登录成功", null);
	}


	/**
	 * 发送access_token作为登录加密手段
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException 
	 */
	@RequestMapping(value = { "/getAccessToken" }, method = { RequestMethod.POST })
	@ResponseBody
	public Map<String,Object> getAccessToken(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, NoSuchAlgorithmException{
		Date now = new Date();
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> resultMap = new HashMap<String,Object>();
		access_token = MD5Util.GetMD5Code(now.getTime()+"");
		resultMap.put("access_token",access_token);
		Date now1 = new Date();
		System.out.println("use getAccessToken result: "+access_token+", cost: " + (now1.getTime() - now.getTime()) + " ms");
		return resultMap;
	}

}
